import polyfill from 'dynamic-polyfill';
import Vue from 'vue';
import VueRouter from 'vue-router';
import ElementUI, { Container, Message } from 'element-ui';
import Login from '@/screens/Login';
import '@/auth/permission';
import '@/screens/home/page-event-bus';
import session from '@/auth/session';
import { APP_NAME } from '@/config/app.config';
import { axios } from '@/api/api';
import VueAxios from 'vue-axios';
import moment from 'moment';
import _ from 'underscore';

// 共享暴露到window, 给以前老代码依赖使用
window.axios = axios;
window._ = _;
window.moment = moment;

Vue.use(ElementUI, { size: 'small' });
Vue.use(VueRouter);
Vue.use(VueAxios, axios);

Object.assign(Vue.prototype, {
  document: window.document,
  DictMan: window.DictMan
});

const router = new VueRouter({
  mode: 'hash',
  base: __dirname,
  routes: [
    {
      path: '/',
      component: () => ({
        component: import('@/screens/home/Home.vue'),
        loading: Container,
        delay: 0
      }),
      beforeEnter(to, from, next) {
        if (session.loggedIn()) {
          next();
        } else {
          next('/login');
        }
      }
    },
    {
      path: '/login',
      component: Login
    }
  ]
});

let app = new Vue({
  render(h) {
    return h('router-view');
  },
  router,
});

polyfill({
  fills: [
    'Promise',
    'String.prototype.endsWith', 'String.prototype.startsWith',
    'Object.assign', 'Object.values',
    ...['find', 'findIndex', 'includes'].map(name => `Array.prototype.${name}`)
  ],
  options: ['gated'],
  afterFill() {
    app.$mount('#app');
    
    // 设置document.title
    if (process.env.NODE_ENV === 'development') {
      document.title = `(开发模式)${APP_NAME}`;
    } else if (!location.hostname.startsWith('service')) {
      document.title = `(测试版)${APP_NAME}`;
    } else {
      document.title = APP_NAME;
    }
  }
});

if (process.env.NODE_ENV == 'development') {
  import('element-ui/lib/message').then(({default: Message}) => {
    if (!BACKEND_SERVER) {
      Message.error({
        duration: 0,
        showClose: true,
        message: '请首先创建配置 /dev/local-config.js，然后再启动Webpack开发服务器，详见文档。\n'
      });
      return;
    }

    let backendServerEnv = {
      'development': '开发',
      'testing': '测试',
      'production': '生产'
    }[BACKEND_SERVER_ENV];
    let type = {
      'development': 'success',
      'testing': 'success',
      'production': 'warning'
    }[BACKEND_SERVER_ENV];
    Message({
      duration: 5000,
      center: true,
      offset: 8,
      iconClass: 'el-message__icon el-icon-coffee-cup',
      customClass: `development-tip el-message--${type}`,
      dangerouslyUseHTMLString: true,
      message: `
        <h4 style="margin:0;margin-bottom:8px">开发模式</h4>
        <p>后端服务器: ${backendServerEnv} <i class="el-icon-connection"></i> ${BACKEND_SERVER}</p>`
    });
  });
}

if (process.env.NODE_ENV == 'production') {
  import('@/generated/build-version').then(module => {
    console.log('%cBuild Version: %s', 'color:#E6A23C', module.buildTime);
  });
}
  
console.log('\n');
console.log(`%cVue ${Vue.version}`, 'color:#42b983');
console.log(`%cElementUI ${ElementUI.version}`, 'color:#409EFF');
console.log('\n');